﻿using Microsoft.Practices.Unity;
using Sasa.QualityTools.CodeAnalysis.Common;
using Sasa.QualityTools.CodeAnalysis.Core.Models;
using Sasa.QualityTools.CodeAnalysis.Core.Views;
using Sasa.QualityTools.CodeAnalysis.Core.VisualStudio;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.ViewModels;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.ViewModels.Configurations;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Commands.Behaviors.Configuration
{
    public class ConfigureSolutiontBehavior : ConfigureBehaviorBase
    {
        private string configurationPath;


        protected override string ConfigurationPath
        {
            get
            {
                return configurationPath;
            }
        }


        public ConfigureSolutiontBehavior(IUnityContainer container)
            : base(container)
        {
        }


        public override void Behave(CommandExecutionContext context)
        {
            var ide = Container.Resolve<IIde>();

            var solution = ide.Solution;
            configurationPath = solution.ConfigurationPath;

            var view = Container.Resolve<ICodeAnalysisConfigurationView>("solution");

            var model = new CodeAnalysisConfigurationViewModel(CodeAnalysisConfiguration.Load(ConfigurationPath));

            FillRuleSets(model);

            model.GenericConfiguration.BrowseRuleSetRequired += delegate
            {
                var path = BrowseRuleSet();
                if (path != null)
                {
                    if (model.GenericConfiguration.RuleSets.Count(o => o.Path == path) == 0)
                    {
                        model.GenericConfiguration.RuleSets.Add(new RuleSetViewModel(new RuleSet(path)));
                    }
                    model.GenericConfiguration.RuleSet = path;
                    solution.AddSolutionFolder(Core.Constants.CodeAnalysisConfigurationDirName).AddFromFile(path);
                }
            };
            model.Saving += delegate
            {
                ide.Checkout(solution.ConfigurationPath);
            };
            model.Saved += delegate
            {
                solution.AddSolutionFolder(Core.Constants.CodeAnalysisConfigurationDirName).AddFromFile(ConfigurationPath);
            };
            model.CloseRequired += delegate
            {
                view.Close();
            };

            view.DataContext = model;
            view.ShowModal();
        }
    }
}
